<template>
  <el-table :data="socialUsers" :show-header="false">
    <el-table-column fixed="left" label="序号" type="default" width="40" />
    <el-table-column align="left" label="社交平台" width="160">
      <template #default="{ row }">
        <img :src="row.img" alt="" class="h-5 align-middle" />
        <span class="mr-5">{{ row.title }}</span>
      </template>
    </el-table-column>
    <el-table-column align="center" label="操作">
      <template #default="{ row }">
        <template v-if="row.openid">
          已绑定
          <XButton class="mr-5" link title="(解绑)" type="primary" @click="unbind(row)" />
        </template>
        <template v-else>
          未绑定
          <XButton class="mr-5" link title="(绑定)" type="primary" @click="bind(row)" />
        </template>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import * as LoginApi from '@/api/base/login'
import * as ProfileApi from '@/api/system/profile'
import { propTypes } from '@/utils/propTypes'
import { SocialTypeEnum } from '@/utils/constants'
import { SocialUserApi } from '@/api/system/social/social_user'

defineOptions({ name: 'UserSocial' })

defineProps({
  activeName: propTypes.string.isRequired
})

interface SocialUser {
  type: number
  openid: string
  title: string
  img: string
}

const message = useMessage()
const socialUsers = ref<SocialUser[]>([])

const initSocialUsers = async () => {
  socialUsers.value = []
  const userProfile = await ProfileApi.getUserProfile()
  for (const i in SocialTypeEnum) {
    const socialUser = { ...SocialTypeEnum[i] }
    if (!socialUser.enabled) continue
    if (userProfile?.socialUsers) {
      for (const j in userProfile?.socialUsers) {
        if (socialUser.type === userProfile?.socialUsers[j].type) {
          socialUser.openid = userProfile?.socialUsers[j].openid
          break
        }
      }
    }
    socialUsers.value.push(socialUser)
  }
}

const bind = async (row: SocialUser) => {
  // 双层 encode 解决钉钉回调 type 参数丢失的问题
  const redirectUri = location.origin + '/user/profile?' + encodeURIComponent(`type=${row.type}`)
  window.location.href = await LoginApi.socialAuthRedirect(row.type, redirectUri)
}

const unbind = async (row: SocialUser) => {
  await SocialUserApi.socialUnbind(row.type, row.openid)
  row.openid = ''
  message.success('解绑成功')
}

const route = useRoute()
const emit = defineEmits<{
  (e: 'update:activeName', v: string): void
}>()

// 双层 encode 需要在回调后进行 decode
function getUrlValue(key: string): string {
  const url = new URL(decodeURIComponent(location.href))
  return url.searchParams.get(key) ?? ''
}

const bindSocial = async () => {
  const type = getUrlValue('type') as any

  if (!type) {
    return
  }

  if (socialUsers.value?.find((user) => user.type == type)?.openid) {
    return
  }

  const code = route?.query?.code as string
  const state = route?.query?.state as string
  if (!code || !state) {
    return
  }
  // 社交绑定
  await SocialUserApi.socialBind(type, code, state)
  message.success('绑定成功')
  await initSocialUsers()
  emit('update:activeName', 'userSocial')
}

onMounted(async () => {
  await initSocialUsers()
  await bindSocial()
})
</script>

<style scoped lang="scss"></style>
